<?php
/** 
 * Created by RisingSun. 
 * User: MarkSpace 
 * Date: 20210822
 * Time: 11:05 
 * 接口模块
 */
namespace app\api\controller;

use  Mscore\Core\Controller;
use  Mscore\Core\Log;
use  Mscore\Core\Lib\Upload;
use  Mscore\Core\Lib\Mailer;
use  Mscore\Core\Lib\Mobile;
use  app\api\model\Login as LoginModel;
use  app\api\model\Common as Common;
use  Mscore\Core\Lang;

class CommonController extends Controller{
   
    /**
     * 初始化自动连接方法
     * @param array __construct 
     * @param array language 
    */
    public function __construct()  
    {    
        $this->header = get_all_headers();
        $this->header['language']=isset($this->header['language'])&&!empty($this->header['language'])?$this->header['language']:config('langs.default');
        Lang::init($this->header['language']);
        $this->success=Lang::get('Success');
        $this->error=Lang::get('Error');
    }   
    
    /**
     * 编辑器上传图片
     * @param array $editor_upload_img 
     * @param array $where 
     */
    public function editor_upload_img(){
      $user = (new LoginModel)->isAuth();
      $icon ='';
      $file = empty(get('folder'))?'folder':get('folder');
      $url= 'static/upload/'.$file.'/'.date('Ym',time());
      if(!is_dir(config('file.path').$url)){
         mkdir(config('file.path').$url, 0777, true); 
      }
      if(!isset($_FILES['file'])){
          return $this->echojson(Lang::get('Uploadempty'));
      }
      $icon = (new Upload)->Uploadfile($_FILES['file'],$url);
      Log::write(sprintf("upload aid=【%s】,name=【%s】,file=【%s】", $user['aid'], $user['username'], $icon),'upfile/',date("y_m_d").".log");
      $this->success['data']=['src'=>'/'.$icon];
      return $this->echojson($this->success);
    }

    /**
     * 上传图片
     * @param array $upload 
     * @param array $where 
     */
    public function uploadbase64(){
      if($this->cross['crossdomain']){
        foreach ($this->cross['crossinfo'] as $key => $value) {
          header($value);
        }
      }
      $user = (new LoginModel)->isAuth();
      $data=post();$files=$data['file'];$icon ='';$hoder=isset($data['folder'])?$data['folder']:'file';
      $url='static/upload/'.$hoder.'/'.date('Ym',time()).'/';
      if(!is_dir(config('file.path').$url)){
          @mkdir(config('file.path').$url, 0777, true); 
      }
      if(empty($files)){
          return $this->echojson(Lang::get('Uploadempty'));
      }
      $icon = (new Upload)->Uploadbase64($files,$url);
      Log::write(sprintf("upload aid=【%s】,name=【%s】,file=【%s】", $user['aid'], $user['username'], $icon),'upfile/',date("y_m_d").".log");
      $this->success['data']=['src'=>'/'.$icon];
      return $this->echojson($this->success);
    }

    /**
     * 上传图片
     * @param array $upload 
     * @param array $where 
     */
    public function uploadimg(){
      $user = (new LoginModel)->isAuth();
      $icon ='';
      $file = empty(get('folder'))?'folder':get('folder');
      $url='static/upload/'.$file.'/'.date('Ym',time());
      if(!is_dir(config('file.path').$url)){
          mkdir(config('file.path').$url, 0777, true); 
      }
      if(!isset($_FILES['file'])){
          return $this->echojson(Lang::get('Uploadempty'));
      }
      $icon = (new Upload)->Uploadimg($_FILES['file'],$url);
      Log::write(sprintf("upload aid=【%s】,name=【%s】,file=【%s】", $user['aid'], $user['username'], $icon),'upfile/',date("y_m_d").".log");
      $this->success['data']=['src'=>'/'.$icon];
      return $this->echojson($this->success);
    }

    /**
     * 上传文件
     * @param array $upload 
     * @param array $where 
     */
    public function upload(){
      $user = (new LoginModel)->isAuth();
      $icon ='';
      $file = empty(get('folder'))?'folder':get('folder');
      $url='static/upload/'.$file.'/'.date('Ym',time());
      if(!is_dir(config('file.path').$url)){
          mkdir(config('file.path').$url, 0777, true); 
      }
      if(!isset($_FILES['file'])){
          return $this->echojson(Lang::get('Uploadempty'));
      }
      $icon = (new Upload)->Uploadfile($_FILES['file'],$url);
      Log::write(sprintf("upload aid=【%s】,name=【%s】,file=【%s】", $user['aid'], $user['username'], $icon),'upfile/',date("y_m_d").".log");
      $this->success['data']=['src'=>'/'.$icon];
      return $this->echojson($this->success);
    }



    /**
     * 签到
     * @param array $signin 
     * @param array $where 
     */
    public function signin(){
      $user = (new LoginModel)->isAuth();
      $signin=new Common();
      $count=$signin->getsign($user['aid']);
      switch (true) {
        case !isset($count['update_time']) || $count['update_time']<date('Y-m-d'):
            $num=isset($count['count'])?$count['count']:0;
            $integras=isset($count['integra'])?$count['integra']:0;
            $integra=$signin->getintegra('content')['content']['signin'];
            $integra=isset($integra)?$integra:0;
            $savedata=[
                'aid'=>$user['aid'],
                'count'=>$num+1,
                'integra'=>$integras+$integra,
                'update_time'=>date('Y-m-d')
            ];
            $signin->signin($num,$savedata);
            return $this->echojson(Lang::get('Signinok'));
            break;
        default:
            return $this->echojson(Lang::get('Signinok'));
            break;
      }
    }

    /**
     * 获取签到
     * @param array $getsign 
     * @param array $where 
     */
    public function getsign(){
      $user = (new LoginModel)->isAuth();
      $signin=new Common();
      $info=$signin->getsign($user['aid']);
      $info=!empty($info)?$info:[];
      $this->success['data']=$info;
      return $this->echojson($this->success);
    }

    /**
     * 获取区域
     * @param array $getarea 
     * @param array $where 
     */
    public function getarea(){
      $user = (new LoginModel)->isAuth();
      $signin=new Common();
      $id=post('id');
      $where='';
      if(isset($id)){
          $where=' pid='.$id;
      };
      $info=$signin->getarea($where);
      $info=!empty($info)?$info:[];
      $this->success['data']=$info;
      return $this->echojson($this->success);
    }

    /**
     * 获取客服
     * @param array $getcuster 
     * @param array $where 
     */
    public function getcuster(){
      $user = (new LoginModel)->isAuth();
      $custer=new Common();
      $page = post('page',1);
      $limit = post('limit',10);
      $where = 'status>0 and type <3 and aid = ' . $user['pid'];
      $info=$custer->getcuster($where,$page,$limit);
      if(empty($info['datalist'])){
          $where = 'status>0 and type <3';
          $info=$custer->getcuster($where,$page,$limit);
      }
      foreach ($info['datalist'] as $key => $value) {
        if(!empty($value['titles'])){
          $info['datalist'][$key]['name']=isset(json_decode($value['titles'],true)[$this->header['language']])?json_decode($value['titles'],true)[$this->header['language']]:$value['name'];
        }
        if(!empty($value['kefu_urls'])){
          $info['datalist'][$key]['kefu_url']=isset(json_decode($value['kefu_urls'],true)[$this->header['language']])?json_decode($value['kefu_urls'],true)[$this->header['language']]:$value['kefu_url'];
        }
        unset($info['datalist'][$key]['titles'],$info['datalist'][$key]['kefu_urls']);
      }
      $this->success['data']=$info['datalist'];
      $this->success['count']=$info['total'];
      return $this->echojson($this->success);
    }

    /**
     * 获取充值客服
     * @param array $getrecuster 
     * @param array $where 
     */
    public function getrecuster(){
      $user = (new LoginModel)->isAuth();
      $custer=new Common();
      $page = post('page',1);
      $limit = post('limit',10);
      $where = 'status>0 and type = 4 ';
      $info=$custer->getcuster($where,$page,$limit);
      foreach ($info['datalist'] as $key => $value) {
        if(!empty($value['titles'])){
          $info['datalist'][$key]['name']=isset(json_decode($value['titles'],true)[$this->header['language']])?json_decode($value['titles'],true)[$this->header['language']]:$value['name'];
        }
        if(!empty($value['kefu_urls'])){
          $info['datalist'][$key]['kefu_url']=isset(json_decode($value['kefu_urls'],true)[$this->header['language']])?json_decode($value['kefu_urls'],true)[$this->header['language']]:$value['kefu_url'];
        }
        unset($info['datalist'][$key]['titles'],$info['datalist'][$key]['kefu_urls']);
      }
      $this->success['data']=$info['datalist'];
      $this->success['count']=$info['total'];
      return $this->echojson($this->success);
    }

    /**
     * 发送验证码 验证用户
     * @param array $sendcode 
     * @param array $where 
     */
    public function sendcode(){
      $email = post('email');
      if(empty($email)) $this->echoJson(Lang::get('Emailempty'));
      $common=new Common();
      $info=$common->getAccount('email="'.$email.'"','email,aid');
      if(!isset($info['email'])&&empty($info['email'])){
          $this->echoJson(Lang::get('Getemailerror'));
          return false;
      }
      $type = !empty(post('type'))?post('type'):'code';
      $template=$common->getBaseinfo('keyname="smstemplate"','content')['content'];
      $template=isset($template[$type])&&!empty($template[$type])?$template[$type]:'';
      if(!empty($template)&&preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/',$info['email'])){
          //整理模版
          $template=explode(':',$template);
          $outtime=isset($template[2])?$template[2]:300;
          $code=getRandStr(4);
          //整理数据发送
          $subject=isset($template[0])?$template[0]:'测试';
          $content=isset($template[1])?$template[1]:'测试测试';
          $search = '{'.$type.'}';
          $content = str_replace($search, '<b>'.$code.'</b>', $content);
          $st=$common->savacode('aid='.$info['aid'],['code'=>$code,'endtime'=>(time()+$outtime),'aid'=>$info['aid'],'email'=>$info['email'],'content'=>$content]);
          if(!$st){
              return $this->echojson($this->error);
          }
          Mailer::send($info['email'],$subject,$content);
      }else{
          return $this->echojson($this->error);
      }
      return $this->echojson($this->success);
    }

    /**
     * 发送验证码 不验证用户
     * @param array $getcode 
     * @param array $where 
     */
    public function getcode(){
      $email = post('email');
      if(empty($email)) $this->echoJson(Lang::get('Emailempty'));
      $common=new Common();
      $type = !empty(post('type'))?post('type'):'code';
      $template=$common->getBaseinfo('keyname="smstemplate"','content')['content'][$type];
      if(!empty($template)&&preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/',$email)){
          //整理模版
          $template=explode(':',$template);
          $outtime=isset($template[2])?$template[2]:300;
          $code=getRandStr(4);
          //整理数据发送
          $subject=isset($template[0])?$template[0]:'测试';
          $content=isset($template[1])?$template[1]:'测试测试';
          $search = '{'.$type.'}';
          $content = str_replace($search, '<b>'.$code.'</b>', $content);
          $st=$common->savacode('email="'.$email.'"',['code'=>$code,'endtime'=>(time()+$outtime),'email'=>$email,'content'=>$content]);
          if(!$st){
              return $this->echojson($this->error);
          }
          Mailer::send($email,$subject,$content);
      }
      return $this->echojson($this->success);
    }

    /**
     * 发送短信验证码 验证用户
     * @param array $sendcode 
     * @param array $where 
     */
    public function sendsms(){
      $mobile = post('mobile');
      if(empty($mobile)) $this->echoJson(Lang::get('Mobileempty'));
      $common=new Common();
      $info=$common->getAccount('mobile="'.$mobile.'"','mobile,aid');
      if(!isset($info['mobile'])&&empty($info['mobile'])){
          $this->echoJson(Lang::get('Getmobileerror'));
          return false;
      }
      $type = !empty(post('type'))?post('type'):'code';
      $template=$common->getBaseinfo('keyname="smstemplate"','content')['content'];
      $template=isset($template[$type])&&!empty($template[$type])?$template[$type]:'';
      if(!empty($template)&&preg_match('/^\d+(_+\d+)*+$/',$info['mobile'])){
          $areacode=$common->getBaseinfo('keyname="mobile"','content')['content']['areacode'];
          $areacode=!empty($areacode)?explode(",", $areacode):[];
          if(empty($areacode)){ $this->echojson($this->error); }
          $mobile = ltrim($mobile, '0');
          if (!preg_match('/'.$areacode[0].'/', $mobile)){
            $mobile = $areacode[0].$mobile;
          }
          if(mb_strlen($mobile, 'UTF-8')!=$areacode[1]){
            return $this->echojson(Lang::get('Getmobileerror'));
          }
          //整理模版
          $template=explode(':',$template);
          $outtime=isset($template[2])?$template[2]:300;
          $code=getRandStr(4);
          
          //整理数据发送
          $content=isset($template[1])?$template[1]:'测试测试';
          $search = '{'.$type.'}';
          $content = str_replace($search, $code, $content);
          $st=$common->savacode('aid='.$info['aid'],['code'=>$code,'endtime'=>(time()+$outtime),'aid'=>$info['aid'],'mobile'=>$info['mobile'],'content'=>$content]);
          if(!$st){
              return $this->echojson($this->error);
          }
          $st=Mobile::send($mobile,$content);
          $st=json_decode($st,true);
          $st['msg']=$st['desc'];unset($st['desc']);
          if($st['code']!='00000'){
            return $this->echojson($st);
          }
      }else{
          return $this->echojson($this->error);
      }
      return $this->echojson($this->success);
    }

    /**
     * 发送短信验证码 不验证用户
     * @param array $getsms 
     * @param array $where 
     */
    public function getsms(){
      $mobile = post('mobile');
      if(empty($mobile)) $this->echoJson(Lang::get('Mobileempty'));
      $mobileinfo=$mobile;
      $common=new Common();
      $type = !empty(post('type'))?post('type'):'code';
      $template=$common->getBaseinfo('keyname="smstemplate"','content')['content'][$type];
      if(!empty($template)&&preg_match('/^\d+(_+\d+)*+$/',$mobile)){
          $areacode=$common->getBaseinfo('keyname="mobile"','content')['content']['areacode'];
          $areacode=!empty($areacode)?explode(",", $areacode):[];
          if(empty($areacode)){ $this->echojson($this->error); }
          $mobile = ltrim($mobile, '0');
          if (!preg_match('/'.$areacode[0].'/', $mobile)) {
            $mobile = $areacode[0].$mobile;
          }
          if(mb_strlen($mobile, 'UTF-8')!=$areacode[1]){
            return $this->echojson(Lang::get('Getmobileerror'));
          }
          //整理模版
          $template=explode(':',$template);
          $outtime=isset($template[2])?$template[2]:300;
          $code=getRandStr(4);
          //整理数据发送
          $content=isset($template[1])?$template[1]:'测试测试';
          $search = '{'.$type.'}';
          $content = str_replace($search, $code, $content);
          $st=$common->savacode('mobile="'.$mobileinfo.'"',['code'=>$code,'endtime'=>(time()+$outtime),'mobile'=>$mobile,'content'=>$content]);
          if(!$st){
              return $this->echojson($this->error);
          }
          $st=Mobile::send($mobile,$content);
          $st=json_decode($st,true);
          $st['msg']=$st['desc'];unset($st['desc']);
          if($st['code']!='00000'){
            return $this->echojson($st);
          }
      }
      return $this->echojson($this->success);
    }

    /**
     * 获取提领金额参数
     * @param array $getpayconfig 
     * @param array $where 
    */
    public function getpayconfig(){
      $common=new Common();
      $where = ' keyname="payment" ';
      $info=$common->getBaseinfo($where,['content'])['content'];
      $info['min']=isset($info['min'])?$info['min']:0;
      $info['max']=isset($info['max'])?$info['max']:0;
      $info['withdrawal']=isset($info['withdrawal'])?$info['withdrawal']:0;
      $this->success['data']=$info;
      return $this->echojson($this->success);
    }
    
    /**
     * 獲取語言
     * @param array $getLang 
     * @param array $where 
    */
    public function getlang(){
      $langs=[];
      $common=new Common(); $where = ' keyname = "lang" ';
      $info=$common->getBaseinfo($where,['content']);
      if(!empty($info['content'])){
        $info=$info['content'];
      }else{
        $langs = config('langs');
        foreach ($langs as $key => $value) {
          $info[$key]= $value['$value'];
        }
        unset($langs);
      }
      $this->success['data']=$info;
      return $this->echojson($this->success);
    }

}